import axios, { Method, CancelTokenSource, AxiosRequestConfig } from "axios";
import { useCallback, useEffect, useMemo, useState } from "react";

export const queries = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_URL,
    withCredentials: true
})

export type ErrorCallback = () => void
export const getQueries = (config: AxiosRequestConfig<any>, callback: ErrorCallback) => {
    return queries(config).then(e => e.data).catch(callback);
}

const useQueries = <T extends string>(url: T, method: Method = "GET") => {
    const [result, setResult] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [source, setSource] = useState<CancelTokenSource>();
    const getData = useCallback(({
        data,
        params,
    }: { data?: any, params?: any } = {}) => {
        const source = axios.CancelToken.source()
        setSource(source);
        queries(url, {
            method,
            cancelToken: source.token,
            data,
            params,
        }).then((e) => {
            setResult(e.data);
        }).catch((e) => {
            setError(e);
        }).finally(() => {
            setLoading(false);
        });
    }, []);
    useEffect(() => {
        return () => {
            source?.cancel("终止请求");
        }
    }, [source]);
    const data = useMemo(() => {
        return [{
            result,
            loading,
            error
        }, getData] as const
    }, [result, loading, error]);
    return data
}
export default useQueries